package com.yc.cloud.openai.portal.task;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.yc.cloud.common.oss.entity.OssFile;
import com.yc.cloud.common.oss.service.OssFileService;
import com.yc.cloud.openai.portal.dao.ComfyUiClient;
import com.yc.cloud.openai.portal.enums.ImageRecordStatusEnums;
import com.yc.cloud.openai.portal.enums.PromptType;
import com.yc.cloud.openai.portal.enums.TextToImageProvider;
import com.yc.cloud.openai.portal.factory.TextToImageClientFactory;
import com.yc.cloud.openai.portal.service.ImageRecordService;
import com.yc.cloud.openai.portal.vo.HistoryVo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.val;
import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
// @ConditionalOnProperty(name = "spring.profiles.active", havingValue = "local")
public class ImageRecordTask {
    private final Map<TextToImageProvider, ComfyUiClient> textToImageClientMap;
    private final ImageRecordService imageRecordService;
    private List<String> statusList;
    private final OssFileService ossFileService;

    public ImageRecordTask(TextToImageClientFactory clientFactory, ImageRecordService imageRecordService,
            OssFileService ossFileService) {
        this.imageRecordService = imageRecordService;
        this.textToImageClientMap = clientFactory.getClientMap();
        this.ossFileService = ossFileService;
        initStatusList();
    }

    @Scheduled(fixedDelay = 10L, timeUnit = TimeUnit.SECONDS)

    // 同步图片AI生成的记录状态
    public void syncImageRecordStatus() {
        val imageRecordList = imageRecordService.listByStatus(statusList);
        if (CollUtil.isNotEmpty(imageRecordList)) {
            for (val imageRecord : imageRecordList) {
                val provider = imageRecord.getProvider();
                val uuid = imageRecord.getUuid();
                if (StrUtil.isEmpty(provider)) {
                    log.error("未知的图片AI提供商 任务ID:{}", imageRecord.getUuid());
                    continue;
                }
                val textToImageClient = textToImageClientMap.get(TextToImageProvider.fromKey(provider));
                if (textToImageClient == null) {
                    log.error("未知的图片AI提供商 :{}", imageRecord.getProvider());
                    continue;
                }
                val images = getTextToImageHistory(textToImageClient, provider, uuid);
                if (CollUtil.isEmpty(images)) {
                    continue;
                }
                val ossFileList = new ArrayList<OssFile>();
                for (val image : images) {
                    val path = image.getPath();
                    if (FileUtil.exist(path)) {
                        imageRecord.setStatus(ImageRecordStatusEnums.FINISHED.getKey());
                        val updateFlag = imageRecordService.updateById(imageRecord);
                        if (updateFlag) {
                            val fileId = ossFileService.generateFileId();
                            val ossFile = ossFileService.buildOssFile(fileId, image.getName(), path);
                            // 使用任务ID作为他的父级文件ID做关联
                            ossFile.setParentFileId(uuid);
                            ossFileList.add(ossFile);
                        }
                    }
                }
                if (CollUtil.isEmpty(ossFileList)) {
                    continue;
                }
                ossFileService.saveBatch(ossFileList);
            }
        }
    }

    /**
     * 获取图片AI生成的历史记录
     *
     * @param textToImageClient 图片AI客户端
     * @param provider          图片AI提供商
     * @param promptId          图片AI任务ID
     * @return 图片AI生成的历史记录
     */
    private List<HistoryVo> getTextToImageHistory(ComfyUiClient textToImageClient, String provider,
            String promptId) {
        val historyResponse = textToImageClient.history(promptId, PromptType.TEXT2IMAGE.getKey());
        if (historyResponse != null && CollUtil.isNotEmpty(historyResponse.getHistoryList())) {
            return historyResponse.getHistoryList();

        }
        return null;
    }

    private void initStatusList() {
        statusList = new ArrayList<>();
        statusList.add(ImageRecordStatusEnums.PENDING.getKey());
        statusList.add(ImageRecordStatusEnums.PROGRESS.getKey());
    }
}
